package com.Service;
import com.Dao.FindBookDao;
import com.Utils.RedisUtil;
import com.Utils.TimestampUtil;
import com.pojo.FindBook;
import com.pojo.FindRemark;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FindBookService {
    @Autowired
    private FindBookDao findBookDaoImp;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TimestampUtil timestampUtil;
    public List<FindBook> findBooksByAuthor(String key ,String flag) throws SQLException {
        return findBookDaoImp.findBooksByAuthor(key,flag);
    }
    public List<FindBook> findAllBooks() {
        return findBookDaoImp.findAllBooks();
    }

    public List<FindBook> findEverybodyLikes() {
        Map<String, Integer> recommendedBooks = redisUtil.getRecommendedBooks();
        List<FindBook> list = new ArrayList<>();
        recommendedBooks.forEach((key,value)->{//根据缓存返回的用户点击前五的书籍类型的遍历，带着这些类型和点击次数去数据库查询数据
            List<FindBook> byTypeAndLimit = findBookDaoImp.findByTypeAndLimit(key, value);
            list.addAll(byTypeAndLimit);
        });
        return list;
    }
    public FindBook findBookDetail(String bookId){
        FindBook bookById = findBookDaoImp.findBookById(bookId);
        redisUtil.recordUserClick(bookById.getMainSignature());//记录用户点击的书的种类次数
        return bookById;
    }
    public List<FindRemark> findBookCommentPage(String bookId, Integer pageNum, Integer pageSize,String currentTime){
        List<FindRemark>remarkList= findBookDaoImp.findBookCommentPage(bookId,pageNum,pageSize,currentTime);
        for(FindRemark remark:remarkList){
            long currenttime=Long.parseLong(currentTime);
            long remarkTime=Long.parseLong(remark.getRemarkTime());
            String result=timestampUtil.getResult(remarkTime,currenttime);
            remark.setResult(result);
        }
        return remarkList;
    }
    public Long findBookCommentCount(String bookId){
        return findBookDaoImp.findBookCommentCount(bookId);
    }
}
